import type { RouteLocationRaw, Router } from 'vue-router'

import { useRouter } from 'vue-router'

import { useUserStore } from '@/store/modules/user'
// import { useWorktabStore } from '@/store/modules/worktab'
import { RoutesAlias } from '@/router/routesAlias'
import { isString } from 'lodash-es'

import { TopModuleKeyEnum } from '@/enums/sysEnum'
import { useMenuStore } from '@/store/modules/menu'

export type RouteLocationRawEx = Omit<RouteLocationRaw, 'path'> & { path: RoutesAlias }

function handleError(e: Error) {
  console.error(e)
}

export function useGo(_router?: Router) {
  const userStore = useUserStore()
  let router
  if (!_router) {
    router = useRouter()
  }
  const {
    push,
    replace
    // currentRoute
  } = _router || router
  // const route = unref(currentRoute)

  const go = (
    opt: RoutesAlias | RouteLocationRawEx | string = userStore.getUserInfo.homePath,
    isReplace = false
    // isCloseCurrTab = false
  ) => {
    if (!opt) {
      return
    }
    function handleCloseCurrTab() {
      // if (isCloseCurrTab) {
      //   const { removeCurrentTab } = useWorktabStore()
      //   removeCurrentTab()
      // }
    }

    if (isString(opt)) {
      isReplace
        ? replace(opt).then(handleCloseCurrTab).catch(handleError)
        : push(opt).then(handleCloseCurrTab).catch(handleError)
    } else {
      const o = opt as RouteLocationRaw
      isReplace
        ? replace(o).then(handleCloseCurrTab).catch(handleError)
        : push(o).then(handleCloseCurrTab).catch(handleError)
    }
  }

  /**
   * 跳转到对应顶级模块
   */
  const goTopModule = (name: TopModuleKeyEnum) => {
    const { menuList } = useMenuStore()
    // 找到有权限的第一个菜单
    const to = menuList.find((v) => v.meta?.topModuleKey == name)
    to && go(to.path)
  }

  return { go, goTopModule }
}
